import { Toast } from 'mint-ui'
export default {
  reduceCartItem (state, id) {
    state.cart = state.cart.map(item => {
      if (item.id === id) {
        if (item.count !== 1) {
          item.count--
        }
      }
      return item
    })
  },
  addCartItem (state, {id, count}) {
    count = count || 1
    state.cart = state.cart.map(item => {
      if (item.id === id) {
        item.count += count
      }
      return item
    })
  },
  status (state, id) {
    state.cart = state.cart.map(item => {
      if (item.id === id) {
        item.checked = !item.checked
      }
      return item
    })
    state.cart.filter((item) => {
      return item.checked
    }
    ).length === state.cart.length
      ? state.allCheck = true
      : state.allCheck = false
  },
  checked (state, val) {
    state.cart.forEach(item => {
      if (val === false) {
        item.checked = true
      } else {
        item.checked = false
      }
    })
    state.allCheck = !state.allCheck
  },
  addToCart (state, {prod, count}) {
    count = count || 1
    const {
      id
    } = prod
    const isInCart = state.cart.some((cartItem) => {
      return cartItem.id === id
    })
    if (isInCart) {
      this.commit('addCartItem', {id, count})
      Toast('添加成功')
    } else {
      state.cart.push({
        ...prod,
        count,
        checked: false
      })
      Toast('添加成功')
    }
    return false
  },
  loginSuccess (state, user) {
    state.user = {
      ...user,
      isLogin: true
    }
  },
  loginOut (state) {
    state.user = {}
    window.localStorage.removeItem('user')
  },
  ShowEdit (state) {
    state.showEdit = true
  },
  CloseEdit (state) {
    state.showEdit = false
  },
  deleteCartItem (state) {
    state.cart = state.cart.filter(item => {
      return (item.checked === false)
    })
    state.showEdit = false
    Toast('删除成功')
  },
  cate (state, data) {
    const {
      id,
      page,
      index
    } = data
    state.cateid = id
    state.catepage = page
    state.cartindex = index
    console.log(state)
  }
}
